<?php

/**
 * 收案分类表
 */

namespace app\common\model;

use MongoDB\BSON\ObjectId;
use app\common\lib\ZhyxMongo;

class CollectClass extends BaseModel
{
    protected $name = "collect_class";

    protected $type = [
        'creator_id' => 'integer',
        'deleted_at' => 'integer',
        'created_at' => 'integer',
        'updated_at' => 'integer',
    ];

    /**
     * 获取分类数据
     */
    public function getLists(int $type, int $creatorId)
    {
        $departId = request()->user()['department_id'];
         $customDeptId = (int)request()->header("custom-dept-id");

        if (!empty($customDeptId)) {
            $departId = $customDeptId;
        }
        
       // $departId = 69;
        $whereOr1 = ['creator_id', '=', $creatorId];
        $whereOr2 = [
            ['department_id', '=', $departId],
            ['share_values.value', 'in', [$creatorId, $departId]],
            ['global_share_values.value', 'in', [$creatorId, $departId]],
        ];

        return $this->field('id,parent_id,className,is_share,manageList,deleted_at,can_delete')
            ->where('type', $type)
            ->where('deleted_at', 0)
            ->whereOr([$whereOr1, function ($query) use ($creatorId) {
                return $query->where([["is_share", "=", 1], ["manageList.id", "=", $creatorId]]);
            }])
            ->whereOr(function ($query) use ($whereOr2) {
                foreach ($whereOr2 as $k => $v) {
                    $query->whereOr([$v]);
                }
            })->order(["id" => 1])
            ->select()->each(function ($item, $key) {
                $item['count'] = isset($item['patientList']) ? count($item['patientList']) : 0;
                  $item['can_delete'] = $item['can_delete'] ?? true;
                return $item;
            })
            ->toTree();

    }

    /**
     * 添加数据
     * @param array $data
     * @return int
     */
    public function addData(array $data): int
    {
        return $this->save($data);
    }

    /**
     * 更新数据
     * @param array $data
     * @return bool
     */
    public function saveData($id, array $data): bool
    {
        $model = self::find($id);
        return $model->save($data);
    }

    /**
     * 删除分类
     */
    public function delClass($id)
    {
        $isId = $this->where('parent_id', $id)->value('id');

        if ($isId) {
            return false;
        } else {
            return self::destroy($id);
        }
    }

    /**
     * 批量分组（作废）
     * @param array $param
     */
//    public function upGrouping(array $param)
//    {
//        $result = ZhyxMongo::getInstance()->setCollection("collect_class")->updateMany([], ['$pullAll' => ['patientList' => $param['id']]]);
//        ZhyxMongo::getInstance()->setCollection("collect_class")->updateMany(["_id" => new ObjectId($param["class_id"])], ['$push' => ['patientList' => ['$each' => $param['id']]]]);
//
//        return true;
//    }

    /**
     * 移除节点数据
     * @param array $pid 患者主键
     * @return bool
     */
    public function pullNode(array $pid): bool
    {
        ZhyxMongo::getInstance()->setCollection("collect_class")->updateMany([], ['$pull' => ["patientList" => ["patient_uuid" => ['$in' => $pid]]]]);
        return true;
    }

    public function bindClass(array $data)
    {
        $arr = [];
        $i = 1;
        // 处理周和疾病数据
        $this->processItems($data["weeks"] ?? [], $data, 0, $arr, $i);
        $this->processItems($data["diseases"] ?? [], $data, 1, $arr, $i);
        return true;
    }

    public function updateClass(array $data, string $id): bool
    {
        $odds = $this->where([["packet_id", "=", $id]])->column("id");
        // 处理周和疾病数据
        $weekIds = $this->processData($data["weeks"] ?? [], $data, 0, $id);
        $diseaseIds = $this->processData($data["diseases"] ?? [], $data, 1, $id);
        //$diseaseIds=[];
        $ids = array_merge($weekIds, $diseaseIds);
        // 删除无用的id
        return $this->where([['id', "in", $odds], ['id', 'not in', $ids]])
                ->save(['deleted_at' => time()]) !== false;
    }

    private function processItems(array $items, array $data, int $platform, array &$arr, int &$i)
    {

        foreach ($items as $item) {
            $saveData[] = $this->prepareData($item, $data, $platform, true, $i);
            $i++;
        }

        return $this->insertAll($saveData);

    }

    private function processData(array $items, array $data, int $platform, string $id = ''): array
    {
        $ids = [];
        foreach ($items as $item) {
            if (isset($item["id"])) {
                $ids[] = $oid = new ObjectId($item["id"]);
                //根据oid判断是否在库中存在
                $isExists = $this->where("id", $item["id"])->count();
                if ($isExists) {
                    $saveData = $this->prepareData($item, $data, $platform);
                    $this->where([["id", "=", $item["id"]]])->save($saveData);
                } else {
                    $prepareData = $data;
                    $prepareData["packet_id"] = $id;
                    $newData = $this->prepareData($item, $prepareData, $platform, true);
                    $this->insert($newData);
                }
            }
        }
        return $ids;
    }

    private function prepareData(array $item, array $data, int $platform, bool $isNew = false, int $sort = 999): array
    {

        $baseData = [
            'className' => $item['name'],
            'department_id' => $data['dept_id'],
            'department_name' => $data['dept_name'],
            'mapping_value' => $platform === 1 ? array_column($item["disease_list"], "title") : $item["value"],
            'sort' => $item['s_no'] ?? $sort,
            'share_type' => $item["share_type"] ?? 0,
            'share_values' => $item["share_values"] ?? [],
            'packet_id' => $isNew ? $data['packet_id'] : $data["id"],
            'global_share_type' => $data['global_share_type'] ?? 0,
            'global_share_values' => $data['global_share_values'] ?? [],
            'deleted_at' => 0,
            'platform' => $platform
        ];

        if ($platform === 1) {
            $baseData['disease_list'] = $item["disease_list"];
        }

        if ($isNew) {

            $baseData['id'] = new ObjectId($item["id"]);
            $baseData['parent_id'] = 0;
            $baseData['xpath'] = '0-' . (string)$baseData['id'];
            $baseData['type'] = 1;
            $baseData['created_at'] = time();
            $baseData['platform'] = $platform;

        }
        return $baseData;
    }

}